const mongoose = require('mongoose');

const WeightSchema = new mongoose.Schema(
  {
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true,
      index: true
    },
    value: {
      type: Number,
      required: true,
      min: [20, '体重不能低于20kg'],
      max: [300, '体重不能超过300kg']
    },
    unit: {
      type: String,
      enum: ['kg', 'lb'],
      default: 'kg'
    },
    measuredAt: {
      type: Date,
      required: true,
      default: Date.now
    },
    bodyFatPercentage: {
      type: Number,
      min: [3, '体脂率不能低于3%'],
      max: [70, '体脂率不能超过70%']
    },
    muscleMass: {
      type: Number,
      min: [10, '肌肉量不能低于10kg'],
      max: [100, '肌肉量不能超过100kg']
    },
    waterPercentage: {
      type: Number,
      min: [20, '水分率不能低于20%'],
      max: [80, '水分率不能超过80%']
    },
    notes: {
      type: String,
      maxlength: 500
    },
    tags: [String],
    isManualEntry: {
      type: Boolean,
      default: true
    },
    deviceInfo: {
      type: String
    },
    bmi: {
      type: Number
    },
    bmiCategory: {
      type: String,
      enum: ['偏瘦', '正常', '超重', '肥胖', '重度肥胖', '极重度肥胖', ''],
      default: ''
    }
  },
  {
    timestamps: true
  }
);

// 创建复合索引，加速按用户和时间范围查询
WeightSchema.index({ user: 1, measuredAt: -1 });

// 计算BMI和BMI分类
WeightSchema.methods.calculateBMI = async function(height) {
  if (!height) {
    return null;
  }
  
  // 如果体重是磅，转换为公斤
  let weightInKg = this.value;
  if (this.unit === 'lb') {
    weightInKg = this.value * 0.453592; // 1磅 = 0.453592公斤
  }
  
  // 计算BMI: 体重(kg) / 身高(m)²
  const heightInMeters = height / 100; // 厘米转米
  const bmi = weightInKg / (heightInMeters * heightInMeters);
  
  this.bmi = parseFloat(bmi.toFixed(1)); // 保留一位小数
  
  // 设置BMI分类
  if (bmi < 18.5) {
    this.bmiCategory = '偏瘦';
  } else if (bmi < 24) {
    this.bmiCategory = '正常';
  } else if (bmi < 28) {
    this.bmiCategory = '超重';
  } else if (bmi < 30) {
    this.bmiCategory = '肥胖';
  } else if (bmi < 40) {
    this.bmiCategory = '重度肥胖';
  } else {
    this.bmiCategory = '极重度肥胖';
  }
  
  return this.bmi;
};

module.exports = mongoose.model('Weight', WeightSchema); 